<!-- 消息页面 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title" :breadCrumb="breadCrumb"> </PageHeaderNew>
    </template>

    <div class="container1">
      <div class="left">
        <div class="search">
          <div class="input">
            <a-input
              v-model="params.name"
              @input="search"
              placeholder="搜索"
              allow-clear
              style="background-color: #f2f3f5"
            >
              <template #prefix>
                <icon-search />
              </template>
            </a-input>
          </div>
          <div class="btn">
            <a-button shape="circle" @click="btnClick">
              <icon-plus />
            </a-button>
          </div>
        </div>
        <div class="personnel">
          <PersonnelList
            :personList="personList"
            v-model:selected="selected"
            @itemClick="itemClick"
          />
        </div>
      </div>
      <div class="right">
        <div v-if="!personnel.data" class="empty">
          <img src="/基泥太美.png" class="img" />
          <div class="tip">今天又是元气满满的一天！</div>
        </div>
        <Chat
          ref="ChatRef"
          v-else
          v-model:person="personnel.data"
          :msgLog="msgLog"
          @send="send"
          @load-more-history="getMsgLog"
          @renew="itemClick"
          :noMore="noMore"
          :msgLogId="msgLogId"
        />
      </div>
    </div>
  </ContentCard>
  <ContactGroupCreate
    v-model:visible="groupCreateVisible"
    @groupCreate="groupCreate"
  />
</template>

<script lang="ts" setup>
import PersonnelList from './components/PersonnelList.vue';
import Chat from './components/Chat.vue';
import { getImMsgLogList } from '@/apis/client/message/index';
import type { Contacts, MsgLogParams } from '@/apis/client/message/type';
import useClientContactsStore from '@/store/modules/client/contacts/index';
import { getImMsgList } from '@/apis/client/message/index';
import webSocket from '@/hooks/webSocket';
import ContactGroupCreate from '../AddressBook/components/ContactGroupCreate.vue';
import {
  contactGroupCreate,
  getContactGroupList
} from '@/apis/client/addressBook/index';
import clonedeep from 'lodash.clonedeep';

const contactsStore = useClientContactsStore();
const ChatRef = ref();
const currUserId = Number(localStorage.getItem('userId'));
const title = '消息';
const breadCrumb = ['消息'];
const personnel = reactive({
  data: {}
});
const selected = ref<number | undefined>(0);
const userId = +(localStorage.getItem('userId') + '');
const itemClick = (person: any, type?: 1) => {
  if (type === 1) {
    ChatRef.value.clearMsg();
  }
  // 区分群消息和个人消息
  const { groupId, listenUserId, id, speakUserId } = person;
  person.unreadNum = 0;
  // getMsgList();
  selected.value = groupId ? groupId : listenUserId;
  //websocket通知后端目前窗口,用于取消未读状态
  const obj = { listenUserId, type: 2, groupId };
  send(obj);
  msgLogParams.groupId = groupId;

  msgLogParams.userId = groupId
    ? void 0
    : listenUserId === userId
    ? speakUserId
    : listenUserId;
  noMore.value = false;
  getMsgLog(0, false);
  personnel.data = person;
};
const msgLogParams = reactive<MsgLogParams>({
  // pageNumber: 0,
  // pageSize: 10,
  userId: 0,
  groupId: 0,
  logId: 0
});
const msgLog = ref<Contacts[]>([]);
const noMore = ref(false);
const msgLogId = ref(0);
/**
 * 获取聊天记录
 * @param
 * msgId 消息id
 * isHistoryMsg 是否是历史消息
 */
const getMsgLog = async (msgId: number, isHistoryMsg = false) => {
  if (noMore.value) return;
  // if (msgId) {
  //   msgLogParams.logId = msgId;
  // } else {
  //   msgLog.value = [];
  //   msgLogParams.logId = 0;
  // }
  // 判断如果是点击不同人或组的消息则要清空消息数据
  if (msgId !== msgLogParams.logId && isHistoryMsg === false) {
    msgLogParams.logId = msgId;
    msgLog.value = [];
  } else if (msgId !== msgLogParams.logId && isHistoryMsg === true) {
    msgLogParams.logId = msgId;
  } else if (msgId) {
    msgLogParams.logId = msgId;
  } else {
    msgLog.value = [];
    msgLogParams.logId = 0;
  }
  const res = await getImMsgLogList(msgLogParams);
  const { totalItems } = res.pageable;
  const list = res.content || [];
  msgLogId.value = res.content[res.content.length - 1].id;
  msgLog.value = [...list, ...msgLog.value];
  // 将重复都id去重，保证消息的唯一
  msgLog.value = Object.values(
    msgLog.value.reduce((uniqueMap: any, item) => {
      if (item.id) {
        uniqueMap[String(item.id)] = item;
      }
      return uniqueMap;
    }, {})
  );
  msgLog.value.forEach((ele) => {
    if (ele.type === 4 && ele.content) {
      try {
        ele.content = JSON.parse(ele.content);
      } catch (error) {
        //l
        console.log('文件类型转换失败');
      }
    }
  });
  if (totalItems === 0) {
    noMore.value = true;
  }
};
const ws = ref();
const { connect, receiveMsg } = webSocket();
onMounted(() => {
  ws.value = connect();
  getMsgList();
});
/**
 * 获取通讯选中的人，群
 */
const getContact = () => {
  const contact: any = contactsStore.contact;
  if (!contact) {
    selected.value = personList.value[0].groupId
      ? personList.value[0].groupId
      : personList.value[0].listenUserId;
    itemClick(personList.value[0]);
    return;
  }
  //如果选择的联系人已存在消息列表里，则提升到首位
  // 如果不存在，则创建在首位
  //查询群聊天
  if (Number(contact.groupId)) {
    const groupIndex = personList.value.findIndex(
      (item) => item.groupId === contact?.id
    );

    if (groupIndex < 0) {
      const { id, name, groupId } = contact;
      personList.value.unshift({
        userId: id,
        groupInfo: {
          id: id,
          name,
          type: 1,
          headPortrait: [
            'https://cbu01.alicdn.com/img/ibank/O1CN01ZmCgdm1vpGhpGgFD6_!!993276221-0-cib.310x310.jpg',
            'https://cbu01.alicdn.com/img/ibank/O1CN01ZmCgdm1vpGhpGgFD6_!!993276221-0-cib.310x310.jpg',
            'https://cbu01.alicdn.com/img/ibank/O1CN01ZmCgdm1vpGhpGgFD6_!!993276221-0-cib.310x310.jpg'
          ]
        },
        groupId: groupId
      });
      selected.value = groupId;
    } else {
      const tempContact = personList.value[groupIndex];
      personList.value.splice(groupIndex, 1);
      personList.value.unshift(tempContact);
    }
  } else {
    //查询个人聊天
    const index = personList.value.findIndex(
      (item) => item.listenUserId === contact?.id
    );
    // 如果没有找到
    if (index < 0) {
      const { id, name, groupId } = contact;
      personList.value.unshift({
        userId: id,
        listenUserId: id,
        listenUser: {
          id: id,
          name,
          type: 1,
          headPortrait:
            'https://cbu01.alicdn.com/img/ibank/O1CN01ZmCgdm1vpGhpGgFD6_!!993276221-0-cib.310x310.jpg'
        },
        speakUserId: currUserId,
        speakUser: {
          id: currUserId,
          name: `${name}2`,
          type: 1,
          headPortrait:
            'https://cbu01.alicdn.com/img/ibank/O1CN01ZmCgdm1vpGhpGgFD6_!!993276221-0-cib.310x310.jpg'
        },
        groupId: groupId
      });
      selected.value = id;
    } else {
      const tempContact = personList.value[index];
      personList.value.splice(index, 1);
      personList.value.unshift(tempContact);
    }
  }

  // 如果是群消息
  if (contact.groupId) {
    msgLogParams.groupId = contact.groupId;
  }

  itemClick(personList.value[0]);
  contactsStore.contact = void 0;
};
const personList = ref<Contacts[]>([]);
const params = reactive({ pageNumber: 0, pageSize: -1, name: '' });
let orginPersonList = ref(); // 储存最初的消息列表数据
/**
 *  获取消息联系人列表
 */
const getMsgList = async () => {
  const res = await getImMsgList(params);
  personList.value = res.content || [];
  personList.value.forEach((item) => {
    try {
      item.content = item.content && JSON.parse(item.content);
    } catch (error) {
      // console.log('error', error);
    }
  });
  orginPersonList.value = res.content || [];
  getContact();
};

// 退出群聊
watch(
  () => contactsStore.isQuitGroup,
  (val: boolean) => {
    if (val) {
      getMsgList();
      contactsStore.isQuitGroup = false;
    }
  }
);
const search = (val: string) => {
  // if (personList.value.groupId) {
  //   personList.value = personList.value.filter((item: any) =>
  //     item.groupInfo?.name.includes(val)
  //   );
  // } else {
  //   personList.value = personList.value.filter(
  //     (item: any) =>
  //       item.listenUser?.nickname.includes(val) ||
  //       item.listenUser?.name.includes(val)
  //   );
  // }
  personList.value = orginPersonList.value.filter((item: any) => {
    if (item.groupId) {
      return item.groupInfo?.name.includes(val);
    } else {
      return (
        item.listenUser?.nickname.includes(val) ||
        item.listenUser?.name.includes(val)
      );
    }
  });

  //
};
//发送消息
const send = (data: any) => {
  //如果存在群id则清空听者id
  if (data.groupId) {
    data.listenUserId = 0;
  }
  ws.value.send(JSON.stringify(data));
  // msgLog.value.unshift(data);
};
watch(
  () => receiveMsg.value,
  (val) => {
    if (!val.content) return;

    // getMsgList();
    //信息不为空，
    if (Number(val.groupId) && selected.value !== Number(val.groupId)) return;
    // 且为选中窗口或为自己发送的消息
    // if (
    //   !Number(val.groupId) &&
    //   Number(val.speakUserId) &&
    //   selected.value !== Number(val.speakUserId)
    // )
    //   return;
    if (val.type === 4) {
      val.content = JSON.parse(val.content);
    }
    msgLog.value.push(val);
  }
);
const groupCreateVisible = ref(false);
const btnClick = () => {
  groupCreateVisible.value = true;
};
//创建群聊
const groupCreate = async (ids: number[]) => {
  // 选中的id然后再加上自己的id
  ids.push(currUserId);
  userId;
  let arr = clonedeep(ids);
  arr = arr.filter((ele) => ele !== userId);
  await contactGroupCreate({ userId: arr });
  getMsgList();
};
</script>

<style lang="less" scoped>
.message-index {
  background: #fff;
  height: 100%;
}
:deep(.ly-card-body) {
  padding: 0 !important;
}
.container1 {
  display: flex;
  height: calc(100vh - 270px);
  .left {
    width: 300px;
    height: 100%;
    // overflow: auto;
    // overflow-x: auto;
    // margin: 0 10px;
    display: flex;
    flex-direction: column;
    .search {
      display: flex;
      align-items: center;
      justify-content: center;
      // border-bottom: 1px solid #eee;
      padding: 10px;
      .input {
        flex: 1;
      }
      .btn {
        margin-left: 10px;
      }
    }
    .personnel {
      flex: 1;
      overflow: auto;
      padding: 0 8px;
      border-right: 1px solid #eee;
    }
  }
  .right {
    flex: 1;
    min-width: 400px;
    background: #f5f5f5;
    // padding: 10px;
    .empty {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      color: #acacac;
      .tip {
        margin-top: 40px;
        font-size: 18px;
      }
    }
  }
}
/* 定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸 */
::-webkit-scrollbar {
  z-index: 100;
  width: 6px;
  height: 6px;
  background-color: #fff;
}

// /* 定义滚动条轨道 内阴影+圆角 */
::-webkit-scrollbar-track {
  z-index: 100;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: inset 0 0 6px rgb(144 147 153 / 30%);
}

// /* 定义滑块 内阴影+圆角 */
::-webkit-scrollbar-thumb {
  z-index: 100;
  background-color: rgb(169 169 169 / 50%);
  border-radius: 10px;
  box-shadow: inset 0 0 6px rgb(144 147 153 / 30%);
}
</style>
